import requests
import helper.sound as sound
import os
from config import config
import common.index as common

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"
}


def __getUrl(word):
    return "https://dict.youdao.com/dictvoice?audio=%s&type=1" % word
    # return 'https://dict.youdao.com/result?word=%s&lang=en' % word


def getAudioOf(word):
    fileName = r"pronounce/%s" % word
    absFilePath = common.getAbsPath(fileName, config)
    isExists = os.path.exists(absFilePath)
    if isExists:
        return absFilePath

    url = __getUrl(word)
    res = requests.get(url, headers=headers)
    with open(absFilePath, "wb") as fp:
        fp.write(res.content)
        # print('读音文件写入成功')

    return absFilePath


def playPronounce(word, seconds=2):
    fileName = getAudioOf(word)
    sound.play(fileName, seconds, True)
    # sound.play(fileName.replace('wav', ''), seconds, True)


if __name__ == "__main__":
    # word = 'pronounce'
    word = "finally"
    playPronounce(word)
